import { PRIORITY_VIEW } from "../../../Core/CoreDefine";
import GViewBase from "../../../Core/GView/GViewBase";
import { AudioMgr } from "../../../Core/Manager/AudioMgr";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import BtlCameraMap from "../../Logic/BtlMap/BtlCameraMap";
import GameMgr from "../../Logic/GameMgr";
import { GCtrl } from './../../../Core/GCtrl';
import { CMsg, PART_BTL_SCENE } from './../../Common/Define';

const { ccclass, property, menu } = cc._decorator;
@ccclass @menu("View/Fight/BattleViewCtrl")
export default class BattleViewCtrl extends GViewBase {
	/** 地图节点 */
	@property(cc.Node) mapRoot: cc.Node = null;

	private _winArgs: ArgsBattleViewCtrl<any> = null;
	private _secenId: number = null;

	onGStart(winArgs: ArgsBattleViewCtrl<any>) {
		this._winArgs = winArgs;
		let tpl = this._winArgs as ArgsBattleViewCtrl<SceneGuanQia>;
		this._secenId = tpl.sceneId;

		let level: SStoryDataRaw | STowerDataRaw = null;
		if (tpl.sceneId === PART_BTL_SCENE.GUANQIA) {
			level = GameMgr.storyData.getRaw<SStoryDataRaw>(tpl.args.level)
		} else {
			level = GameMgr.towerData.getRaw<STowerDataRaw>(tpl.args.level)
		}

		let audio = Res.audio.battle + "battle_" + level.music;
		AudioMgr.Ins().playMusic(audio);
		GameMgr.mapMgr.mapId = level.mapld;
		this.initMapLayer();
	}

	onGLoad() {
		GCtrl.ES.on(CMsg.client.fight_ui.onRetreatClick, this, this.onRetreatClick.bind(this), PRIORITY_VIEW);
		GCtrl.ES.on(CMsg.client.fight_ui.onFinishSettle, this, this.onRetreatClick.bind(this), PRIORITY_VIEW);
		this.node.setContentSize(GCtrl.actualSize);
	}

	protected initMapLayer() {
		this.assetImpl.prefab(Res.prefab.vw.fight.mapLayer, (Prefab) => {
			if (!this.isValid) return;
			this.mapRoot.destroyAllChildren();
			let node = cc.instantiate(Prefab);
			this.mapRoot.addChild(node);
			node.setContentSize(cc.winSize);
			let mapLayer = node.getComponent(BtlCameraMap);
			mapLayer.setBattle(this._winArgs);
			mapLayer.startLoadData();
		})
	}

	protected onRetreatClick() {
		this.onClose();
		switch (this._secenId) {
			case PART_BTL_SCENE.GUANQIA: {
				let tpl = this._winArgs as ArgsBattleViewCtrl<SceneGuanQia>;

				GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.mainPage)
				break;
			}
			case PART_BTL_SCENE.ARENA: {
				let tpl = this._winArgs as ArgsBattleViewCtrl<SceneGuanQia>;

				break;
			}
		}
	}
}
